package com.meitutest.autoscript.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.support.test.InstrumentationRegistry;

import java.util.List;
import java.util.Random;

/**
 * Wifi相关操作
 */
public class WifiUtils {
    private static String targetSsid_ht = "Meitu.cs.hw";
    private static String targetPsd_ht = "mt13333331";
    private static WifiInfo wifi_ht = new WifiInfo(targetSsid_ht, targetPsd_ht,
            WifiEncType.WPA);

    private static String targetSsid_test1 = "Meitu.guest";
    private static String targetPsd_test1 = "mt5320520";
    private static WifiInfo wifi_test1 = new WifiInfo(targetSsid_test1, targetPsd_test1,
            WifiEncType.WPA);


    private static boolean wifiOn;
    private static WifiManager wifiManager = (WifiManager) InstrumentationRegistry.getContext().getSystemService(Context.WIFI_SERVICE);

    /**
     * 网络的加密类型
     */
    private enum WifiEncType {
        WEP, WPA, OPEN
    }

    /**
     * wifi热点的各项信息
     */
    private static class WifiInfo {
        /**
         * 热点名称
         */
        String ssid;
        /**
         * 热点密码
         */
        String psd;
        /**
         * 热点加密类型
         */
        WifiEncType enc;

        WifiInfo(String ssid, String psd, WifiEncType enc) {
            this.ssid = ssid;
            this.psd = psd;
            this.enc = enc;
        }
    }

    /**
     * 获取当前可用的wifi热点
     *
     * @return wifi热点信息
     */
    private static WifiInfo getTargetWifiInfo() {

        if (new Random().nextBoolean())
            return wifi_ht;
        else
            return wifi_test1;

    }


    /**
     * 根据wifi的情况进行环境调整
     */
    public static void adaptWifiConditon() {
        TestReport.f("wifi", "正在调整wifi...");
        // 如果wifi没开启，则开启
        if (!wifiOn)
            turnWifiOn();
        Context context = InstrumentationRegistry.getContext();
        ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo.State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
        wifiOn = wifi == NetworkInfo.State.CONNECTED
                || wifi == NetworkInfo.State.CONNECTING;
        WifiManager wifi_service = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        android.net.wifi.WifiInfo wifiInfo = wifi_service.getConnectionInfo();
        String currentSsid = wifiInfo.getSSID();
        // 当前接入点不是目标接入点,则自动连接指定wifi
        if (!currentSsid.equals("\"" + targetSsid_test1 + "\"")
                || !currentSsid.equals("\"" + targetSsid_ht + "\"")) {
            WifiInfo winfo = getTargetWifiInfo();
            if (wifi == null) {
                TestReport.f("wifi", "目标wifi不存在！");
                return;
            }
            connectSpecificWifi(winfo.ssid, winfo.psd, winfo.enc);
        }

    }


    /**
     * 连接到指定wifi热点
     *
     * @param targetSsid 热点名称，如Meitu.test01
     * @param targetPsd  热点密码，如mt55555555
     * @param enc        热点的加密类型，参考{@link WifiEncType}
     */

    private static void connectSpecificWifi(String targetSsid, String targetPsd,
                                            WifiEncType enc) {
        // 1、注意热点和密码均包含引号，此处需要需要转义引号
        String ssid = "\"" + targetSsid + "\"";
        String psd = "\"" + targetPsd + "\"";

        // 2、配置wifi信息
        WifiConfiguration conf = new WifiConfiguration();
        conf.SSID = ssid;
        switch (enc) {
            case WEP:
                // 加密类型为WEP
                conf.wepKeys[0] = psd;
                conf.wepTxKeyIndex = 0;
                conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
                break;
            case WPA:
                // 加密类型为WPA
                conf.preSharedKey = psd;
                break;
            case OPEN:
                // 开放网络
                conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        }

        // 3、确保wifi已经打开，再连接wifi
        turnWifiOn();
        List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
        if (list == null)
            return;
        // 如果目标热点已经保存，则直接连接
        for (WifiConfiguration i : list) {
            if (i.SSID != null && i.SSID.equals(ssid)) {
                wifiManager.disconnect();
                wifiManager.enableNetwork(i.networkId, true);
                wifiManager.reconnect();
                return;
            }
        }

        // 如果目标热点没有保存过，则先添加再连接
        wifiManager.addNetwork(conf);
        list = wifiManager.getConfiguredNetworks();
        //防止网络没有及时更新到列表造成的空指针异常
        if (list == null || list.size() < 1)
            return;
        for (WifiConfiguration i : list) {
            if (i.SSID != null && i.SSID.equals(ssid)) {
                wifiManager.disconnect();
                wifiManager.enableNetwork(i.networkId, true);
                wifiManager.reconnect();
                return;
            }
        }
    }

    /**
     * 开启WIFI
     */
    private static void turnWifiOn() {
        if (!wifiManager.isWifiEnabled())
            wifiManager.setWifiEnabled(true);
    }


}
